package baidu.bms.consumer;

import baidu.bms.DemoServiceProvider;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpMessageConverterExtractor;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author sunqiyuan
 * @Classname CallDemoService
 * @Description TODO
 * @Date 2020/10/14 10:19 上午
 * @Version V1.0
 */
@Component
public class CallDemoService {

    AtomicInteger count = new AtomicInteger(0);
    //    @DubboReference(version = "${demo.service.version}",services = "annotation-provider")
    // check 不在boot启动时检查，该接口是否启动， lazy 懒加载
    @DubboReference(version = "${demo.service.version}", check = false, lazy = true)
    private DemoServiceProvider demoServiceProvider;

    @Value("${dubbo.application.name}")
    private String serviceName;

    public String doSayHello() {

        //traceId

        String traceId = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        if (count.getAndAdd(1) % 2 == 0) {


            return getForObjectWithHeader(traceId);

        } else {
            // dubbo call dubbo
            String param = String.format("[%s : tid %s : dubboclient]", serviceName, traceId);
            RpcContext.getContext().setAttachment("traceId", traceId);
            return demoServiceProvider.methodA(param);
        }

    }

    public String getForObjectWithHeader(String traceId) {

        String param = String.format("[%s : tid %s : httpclient]", serviceName, traceId);
        String uri = "http://localhost:8082/methodA?name=" + param;
        // dubbo call http
        RestTemplate call = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.add("traceId", "[" + traceId + "]");

        //String a = call.postForObject(uri, new HttpEntity<String>(headers), String.class);

        // 模仿 postForObject 把 method 改成 get
        RequestCallback requestCallback = call.httpEntityCallback(new HttpEntity<String>(headers), String.class);
        HttpMessageConverterExtractor<String> responseExtractor =
                new HttpMessageConverterExtractor<>(String.class, call.getMessageConverters());

        String result = call.execute(uri, HttpMethod.GET, requestCallback, responseExtractor);
        return result;
    }

}
